<template>
  <div>
    <t-button size="large" @click="OnClick" theme="warning">
      <template #icon>
        <Edit1Icon/>
      </template>
      修改登录密码
    </t-button>

    <t-drawer v-model:visible="data.show" header="修改登录密码" :closeOnOverlayClick="false"
              :on-confirm="handleConfirm" @close="handleClose" size="large" destroy-on-close
              confirmBtn="确认修改登录密码">
      <div>
        <t-space direction="vertical" style="width: 100%;">
          <t-input-adornment prepend="账号信息">
            <t-input v-model="userStore.Profile.user.username" readonly
                     placeholder="必须是小写英文字母，不能有空格，比如：root" size="large"/>
          </t-input-adornment>
          <t-input-adornment prepend="旧的密码">
            <t-input v-model="data.formData.old" placeholder="该账号的旧登录密码" type="password" size="large"/>
          </t-input-adornment>
          <t-input-adornment prepend="新的密码">
            <t-input v-model="data.formData.new_pwd" placeholder="新的登录密码，密码长度不低于 6 位。" type="password"
                     size="large"/>
          </t-input-adornment>
          <t-input-adornment prepend="再次输入">
            <t-input v-model="data.formData.new_pwd2" placeholder="再次输入新的登录密码，密码长度不低于 6 位。"
                     type="password" size="large"/>
          </t-input-adornment>
          <template v-if="data.formData.new_pwd !== ''">
            <template v-if="data.formData.new_pwd !== data.formData.new_pwd2">
              <t-alert theme="error">两次输入的新密码不一样</t-alert>
            </template>
          </template>
        </t-space>
      </div>
    </t-drawer>
  </div>
</template>
<script lang="ts" setup>
import {Edit1Icon} from "tdesign-icons-vue-next";
import {reactive} from "vue";
import api from "../../../../api/api";
import {getUserStore} from "../../../../store/modules/user";
import NotificationPlugin from "tdesign-vue-next/es/notification/plugin";

const userStore = getUserStore()

const emits = defineEmits(['success'])
const data = reactive({
  show: false,
  formData: {
    old: "",
    new_pwd: "",
    new_pwd2: ""
  }
})

const OnClick = async () => {
  data.show = true
  data.formData.old = ""
  data.formData.new_pwd = ""
  data.formData.new_pwd2 = ""
}

const handleClose = () => {
  data.show = false
}

const handleConfirm = async () => {
  let res = await api.User.UpdatePassword({
    user: userStore.Profile.user.username,
    pwd: data.formData.old,
    new_pwd: data.formData.new_pwd
  })
  if (res != null) {
    data.show = false
    await NotificationPlugin.success({
      title: '成功',
      content: '密码修改成功'
    })
    emits("success")
  }
}
</script>